package run.iget.framework.common.deserializer;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import run.iget.framework.common.util.DateUtils;
import run.iget.framework.common.util.ExceptionThrowUtils;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * 将入参中的字符串解析为Date
 * ---------------类描述-----------------
 *
 * @author 大周
 * @date 2023/8/16 14:37
 */
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class StringToDateDeserializer extends JsonDeserializer<Date> implements ContextualDeserializer {
    /**
     * 字段注解
     */
    private JsonFormat jsonFormat;

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JacksonException {
        try {
            if (Objects.nonNull(jsonFormat) && StrUtil.isNotBlank(jsonFormat.pattern())) {
                return DateUtils.parse(jsonParser.getText(), jsonFormat.pattern());
            }
            return DateUtils.tryParse(jsonParser.getText());
        } catch (Exception e) {
            log.debug("入参日期解析错误", e);
            ExceptionThrowUtils.of("日期格式错误");
        }
        return null;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property) throws JsonMappingException {
        JsonFormat ann = property.getAnnotation(JsonFormat.class);
        if (ann != null) {
            return new StringToDateDeserializer(ann);
        }
        return this;
    }
}
